import java.util.ArrayList;
import java.util.List;

public class Solution515 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ans=new ArrayList<>();
        dfs(root,ans,0);
        return ans;
    }

    private void dfs(TreeNode root, List<Integer> ans, int deep) {
        if (root==null){
            return;
        }
        if (ans.size()==deep){
            ans.add(root.val);
        }else{
            ans.set(deep,Math.max(ans.get(deep),root.val));
        }
        dfs(root.left,ans,deep+1);
        dfs(root.right,ans,deep+1);
    }

    public static void main(String[] args) {
        System.out.println(new Solution515().largestValues(new TreeNode(1,new TreeNode(3,new TreeNode(5),new TreeNode(3)),new TreeNode(2,null,new TreeNode(9)))));
    }
}
